import cart from'./json/products.json'
import '../cart/style.css'
import { useReducer} from 'react'
const reduce=(state,action)=>{
   switch(action.type){
     case 'add':
      const findIndex = state.findIndex((item) => item.id === action.payload)
      if (findIndex !== -1) {
        return [...state.slice(0, findIndex), { ...state[findIndex], count: state[findIndex].count + 1 }, ...state.slice(findIndex + 1)]
      } else {
        return [
          ...state,
          {...cart.find((p) => p.id === action.payload),  count: 1,}]}
        case'remove':
        return state.filter(item=>item.id!==action.payload)
        case'addCount':
        const countIndex=state.find(item=>item.id===action.payload)
        // console.log(countIndex.count)
        // return [state.slice(0,countIndex.count+=1)]
          return [...state.slice(0, countIndex),
              countIndex,
            ...state.slice(0,countIndex.count+=1)
          ]
        case'all':
        return[]  
          default:
       return state 
   } 
}
const Catr=()=>{
     

  const sum = (state)=>{
    return state.reduce((sum,item)=>sum+item.price,0)
  }
  const isitState = []
  const [state,dispatch]=useReducer(reduce,isitState)
  return(

   <div className="content">
  <div className="left">
    <h2>商品列表</h2> 
    <div className="plist">
     <ul>
      {cart.map(carts=><li className='commodity' key={carts.id}>
      <div className="item">
        <div className="title">{carts.name}</div>
        <img src={carts.image} alt='' />
        <div className="price">
          <button  onClick={()=>dispatch({type:'add',payload:carts.id})} className="add-cart-btn">{carts.price}元 加入购物车</button>
        </div>
        </div>
        </li>)}</ul>
    </div>
  </div>
  <div className="right">
    <h2>购物车<button className="cart-clr-btn" onClick={()=>{dispatch({type:'all'})}} >清空购物车</button></h2>
    <div className="cart" >
      {
        state.map(item=>(<div className="cart-item" key={item.id}>
        <div className="title">{item.name}</div>
        <img src={item.image} alt='' />
        <div className>数量：<input type="number" value={item.count} size={3} onClick
        ={(e)=>
          {e.preventDefault()
          dispatch({type:'addCount',payload:item.id})}} /></div>
        <div>价格{item.price}</div>
        <div><button className="remove-cart-btn"  onClick={()=>{dispatch({type:'remove',payload:item.id})}}>删除</button></div>
      </div>
                    ))}
      <div>总价:{sum(state)}</div>


      </div>
  </div>
</div>

    )
}

const CatrDome=()=>{
  return(<Catr cart={cart}></Catr>)
}
export default CatrDome